<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { UserApi } from '@/api-services/apis/user-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { REG_PWD, REG_USER_NAME } from '@/constants/reg';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { NetoKit } from '@/typings/neto';
import { ApiSysLocalizationInput, SysemailsendrecordApi } from '@/api-services';
import dayjs, { Dayjs } from 'dayjs';
import { SyslocalizationApi } from '@/api-services/apis/syslocalization-api';

defineOptions({
  name: 'SysManageSysNoticeModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  editId?: number | undefined;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation} = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    //新建通知
    add: $t('page.sysLocalization.add'),
    //编辑通知
    edit: $t('page.sysLocalization.edit')
  };
  return titles[props.operateType];
});

type Model = NetoKit.NullToUndefined<Pick<ApiSysLocalizationInput, 'id' | 'title' | 'remark'>>
const model = ref(createDefaultModel());
// string转换为number
// model.value.roleIds = model.value.roleIdStr?.split(',').map(Number);
function createDefaultModel(): Model {
  return {
    id: 0,
    title: '',
    remark: '',
  }
}



async function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.editId) {
    const [err, res] = await feature(getAPI(SyslocalizationApi).get(props.editId));
    queryDone(err, () => {
      const data = res?.data.data;
      if (data) {
        Object.assign(model.value, data);

      }
    })
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();


  const input: ApiSysLocalizationInput = {
    ...model.value
  }



  if (props.operateType === 'add') {
    const [err, res] = await feature(getAPI(SyslocalizationApi).insert(input));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.addSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  } else {
    const [err, res] = await feature(getAPI(SyslocalizationApi).update(input));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  }

}
type RuleKey = Extract<keyof Model, 'title'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  title: defaultRequiredRule
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" modal-height="" width="600px">
    <ElForm ref="formRef" label-width="auto" :model="model" :rules="rules">
      <ElRow :gutter="16" wrap>
        <!-- 标题 -->
        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.sysLocalization.title')" name="title">
            <ElInput v-model="model.title" :placeholder="$t('page.sysLocalization.form.title')" />
          </ElFormItem>
        </ElCol>
        <!-- 备注 -->
        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.manage.common.remark')" name="remark">
            <ElInput type="textarea" v-model="model.remark" :auto-size="{ minRows: 3 }" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
